import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Typography,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { API } from '../../../helpers';

const { Title } = Typography;
const { TextArea } = Input;

const APIForward = () => {
  const [configs, setConfigs] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState(null);
  const [form] = Form.useForm();
  const [channels, setChannels] = useState([]);
  const [channelMap, setChannelMap] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取配置列表
  const fetchConfigs = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const res = await API.get('/api/api_forward', {
        params: { page, page_size: size },
      });
      const { success, data } = res.data;
      if (success && data && data.items) {
        setConfigs(data.items || []);
        setTotal(data.total || 0);
      } else {
        console.warn('API响应格式异常:', res.data);
        // 如果数据存在但格式不对，尝试兼容处理
        if (data && Array.isArray(data)) {
          setConfigs(data);
          setTotal(data.length);
        } else if (data && data.configs) {
          setConfigs(data.configs);
          setTotal(data.total || data.configs.length);
        } else {
          message.error('获取配置列表失败：数据格式错误');
        }
      }
    } catch (error) {
      console.error('获取配置列表错误:', error);
      message.error('获取配置列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取转发渠道列表（类型=52）
  const fetchForwardChannels = async () => {
    try {
      const res = await API.get('/api/channel', {
        params: { page: 1, page_size: 1000, type: 52 },
      });
      const { success, data } = res.data || {};
      if (success && data && Array.isArray(data.items)) {
        setChannels(data.items);
        const map = {};
        data.items.forEach((ch) => {
          map[ch.id] = ch.name || `#${ch.id}`;
        });
        setChannelMap(map);
      }
    } catch (e) {
      // 忽略错误
    }
  };

  // 创建或更新配置
  const handleSubmit = async (values) => {
    try {
      if (editingConfig) {
        // 更新
        await API.put('/api/api_forward', { ...values, id: editingConfig.id });
        message.success('配置更新成功');
      } else {
        // 创建
        await API.post('/api/api_forward', values);
        message.success('配置创建成功');
      }
      setModalVisible(false);
      form.resetFields();
      setEditingConfig(null);
      fetchConfigs(currentPage, pageSize);
    } catch (error) {
      message.error(editingConfig ? '更新失败' : '创建失败');
    }
  };

  // 删除配置
  const handleDelete = async (id) => {
    try {
      await API.delete(`/api/api_forward/${id}`);
      message.success('删除成功');
      fetchConfigs(currentPage, pageSize);
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 编辑配置
  const handleEdit = (record) => {
    setEditingConfig(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 新建配置
  const handleAdd = () => {
    setEditingConfig(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      fixed: 'left',
    },
    {
      title: 'API路径',
      dataIndex: 'api_path',
      key: 'api_path',
      width: 150,
      ellipsis: true,
    },
    {
      title: '目标URL',
      dataIndex: 'target_url',
      key: 'target_url',
      width: 250,
      ellipsis: true,
    },
    {
      title: '转发渠道',
      dataIndex: 'channel_id',
      key: 'channel_id',
      width: 160,
      render: (id) => (id ? channelMap[id] || `#${id}` : '-'),
    },
    {
      title: '费用',
      dataIndex: 'cost',
      key: 'cost',
      width: 80,
      align: 'center',
      render: (cost) => `$${cost.toFixed(4)}`,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      align: 'center',
      render: (isActive) => <Switch checked={isActive} disabled size='small' />,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 120,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      align: 'center',
      render: (_, record) => (
        <Space size='small'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size='small'
          >
            编辑
          </Button>
          <Popconfirm
            title='确定要删除这个配置吗？'
            onConfirm={() => handleDelete(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' danger icon={<DeleteOutlined />} size='small'>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchConfigs();
    fetchForwardChannels();
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row
          justify='space-between'
          align='middle'
          style={{ marginBottom: '16px' }}
        >
          <Col>
            <Title level={3} style={{ margin: 0 }}>
              API转发配置
            </Title>
          </Col>
          <Col>
            <Button type='primary' icon={<PlusOutlined />} onClick={handleAdd}>
              新建配置
            </Button>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={configs}
          rowKey='id'
          loading={loading}
          scroll={{ x: 1200 }}
          size='small'
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
              fetchConfigs(page, size);
            },
          }}
        />
      </Card>

      <Modal
        title={editingConfig ? '编辑配置' : '新建配置'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingConfig(null);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout='vertical'
          onFinish={handleSubmit}
          initialValues={{
            is_active: true,
            cost: 0.01,
          }}
        >
          <Form.Item
            name='api_path'
            label='API路径'
            rules={[
              { required: true, message: '请输入API路径' },
              { pattern: /^\/.+/, message: 'API路径必须以/开头' },
            ]}
          >
            <Input placeholder='例如: /mj-fast' />
          </Form.Item>

          <Form.Item
            name='target_url'
            label='目标转发URL（可选，如果选择了渠道，此项作为路径前缀）'
          >
            <Input placeholder='例如: https://api.geekai.pro/mj-fast' />
          </Form.Item>

          <Form.Item
            name='model_name'
            label='模型名称（用于日志展示，可选）'
            tooltip='填写后将作为日志中的模型名称展示；不填则显示为 forward:{api_path}'
          >
            <Input placeholder='例如：moark-text-moderation' />
          </Form.Item>

          <Form.Item name='channel_id' label='选择转发渠道（可选）'>
            <Select
              placeholder='选择一个转发渠道（类型：转发渠道）'
              allowClear
              options={channels.map((c) => ({
                value: c.id,
                label: `${c.name || '#' + c.id}（#${c.id}）`,
              }))}
              showSearch
              filterOption={(input, option) =>
                (option?.label ?? '')
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Form.Item
            name='cost'
            label='每次调用费用 (USD)'
            rules={[
              { required: true, message: '请输入费用' },
              { type: 'number', min: 0, message: '费用必须大于等于0' },
            ]}
          >
            <InputNumber
              placeholder='0.01'
              min={0}
              step={0.001}
              precision={4}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item name='is_active' label='是否启用' valuePropName='checked'>
            <Switch />
          </Form.Item>

          <Form.Item name='description' label='描述'>
            <TextArea rows={3} placeholder='请输入配置描述' />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type='primary' htmlType='submit'>
                {editingConfig ? '更新' : '创建'}
              </Button>
              <Button
                onClick={() => {
                  setModalVisible(false);
                  setEditingConfig(null);
                  form.resetFields();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default APIForward;
